package com.societyGames.flashForms
{
import com.societyGames.system.EventObject;

import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;

public class VerticalStackContainer extends Sprite implements IChangeSize
{
  private var _desiredHeight:Number;
  private var _desiredWidth:Number;
  private var _sizeChangedEventObject:EventObject;
  private var _items:Vector.<DisplayObject> = new Vector.<DisplayObject>();

  public function VerticalStackContainer()
  {
    this._sizeChangedEventObject = new EventObject(this, "SIZE_CHANGED");
  }

  public function addItem(item:DisplayObject):void
  {
    removeItem(item);
    _items.push(item);
    var changeSize:IChangeSize = item as IChangeSize;
    if (changeSize != null)
    {
      changeSize.sizeChangedEventObject.addEventListener(itemChangedSizeHandler);
    }
    calculate();
  }

  public function removeItem(item:DisplayObject):void
  {
    var index:int = this._items.indexOf(item);
    if (index != -1)
    {
      this._items.slice(index, 1);
      var changeSize:IChangeSize = item as IChangeSize;
      if (changeSize != null)
      {
        changeSize.sizeChangedEventObject.removeEventListener(itemChangedSizeHandler);
      }
      calculate();
    }
  }

  public function clearItems():void
  {
    for each (var item:DisplayObject in this._items)
    {
      this.removeChild(item);
    }
    this._items.length = 0;
    calculate();
  }

  //Make all of the items in _items appear correctly.
  private function calculate():void
  {
    //Wipe the children clean.
    while (this.numChildren > 0)
    {
      this.removeChildAt(this.numChildren - 1);
    }
    //Now re-add children back.
    var nextY:Number = 0;
    for each (var item:DisplayObject in this._items)
    {
      item.x = 0;
      item.y = nextY;
      this.addChild(item);
      nextY += item.height;
    }
    calculateWidth();
    this._sizeChangedEventObject.dispatchEvent();
  }

  private function calculateWidth():void
  {
    for each (var item:DisplayObject in this._items)
    {
      item.width = this._desiredWidth;
    }
  }

  //IChangeSize-->
  public function get sizeChangedEventObject():EventObject
  {
    return this._sizeChangedEventObject;
  }

  //<--IChangeSize

  public override function set height(value:Number):void
  {
    if (value != this._desiredHeight)
    {
      this._desiredHeight = value;
    }
  }

  //The width is pretty much ignored. Perhaps we should try to scale everything down equally to match the width?
  public override function set width(value:Number):void
  {
    if (value != this._desiredWidth)
    {
      this._desiredWidth = value;
      calculateWidth();
    }
  }

  private function itemChangedSizeHandler(event:Event):void
  {
    calculate();
  }
}
}